package com.kds.changzhou.handler;

import cn.hutool.core.exceptions.ExceptionUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 孔德嵩
 */
@Slf4j
public class PackageDecoder extends ByteToMessageDecoder {

    private HandlerConfig handlerConfig;

    private final CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();

    public PackageDecoder(HandlerConfig handlerConfig) {
        this.handlerConfig = handlerConfig;
    }

    /**
     * 常州的通信协议是不加壳加密的报文，裸xml
     * @param ctx           the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
     * @param in            the {@link ByteBuf} from which to read data
     * @param out           the {@link List} to which decoded messages should be added
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        if (in.readableBytes() < 4) {
            // 不足4个字节，等待更多的数据
            return;
        }

        // 读取数据到一个byte数组中
        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);

        // 将byte数组转换为字符串
        String xml = decoder.decode(ByteBuffer.wrap(bytes)).toString();

        in.discardReadBytes();

        log.info("接收到的xml报文:\n\033[34m{}\033[0m",xml);
        // 添加解码后的字符串到输出列表中
        out.add(xml);


    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);

        log.error(ExceptionUtil.stacktraceToString(cause));
        ctx.close();

    }
}
